layui.config({
     base: CXL.ctxPath + '/layuiadmin/' //静态资源所在路径
  }).extend({
    index: 'lib/index' //主入口模块
  }).use(['index', 'form','treetable'], function(){
	  var form = layui.form;
	  var admin = layui.admin;
	  var table = layui.table;
	  var treetable = layui.treetable;
	  var $ = layui.$;

	  var materialNoArray = [];
      var materialNameArray = [];


    //下拉菜单
      var dropdown = layui.dropdown;

    $(document).ready(function (){
        //初始化操作
        $.ajax({
            type: "post",
            url: CXL.ctxPath + '/sys/addTask/initMaterialInfo',
            success: function(res) {
                if(res.success) {
                    var list = res.obj;
                    if(list != null){
                        for(var i = 0;i<list.length;i++){
                            var materialNoInfo = {title:list[i].materialNo,id:list[i].materialName};
                            var materialNameInfo = {title:list[i].materialName,id:list[i].materialNo};
                            materialNoArray.push(materialNoInfo) ;
                            materialNameArray.push(materialNameInfo) ;

                        }
                    }
                }

            }
        });
    });



    var editable = function(d){
        if(d.parentId != '-1'){
            return 'text'; // 这里假设以 editable 字段为判断依据
        }
    };

      var Page = {
                  tableId: 'area-info',
                  url:CXL.ctxPath + '/sys/area/infoList',
                  queryUrl:CXL.ctxPath + '/sys/area/query/id',
                  //addUrl:CXL.ctxPath + '/sys/area/addIndex',
                  addUrl:CXL.ctxPath + '/sys/area/openAdd',
                  toolbar:'#sys-area-toolbar',
                  initColumn:function(){
                      return [[
                          {type:'radio',name:'choose',width:'3%'},
                          {field:'idKey',title:'idKey',hide:true,width:'1%'},
                          {field:'parentId',title:'parentId',hide:true,width:'1%'},
                          {type : 'numbers',title : '序号',width:'3%'},
                          {field:'areaName',title:'库区名称',width:'8%',edit: editable},
                          {field:'stockMaterialNo',title:'物料编码',width:'8%',templet:"#materialNo-dropdpwn"},
                          {field:'stockMaterialName',title:'物料名称',width:'12%',templet:"#materialName-dropdpwn"},
                          {field:'spanName',title:'所属跨区',width:'5%'},
                          {field:'spanNo',title:'所属编码',hide:true,width:'1%'},
                          {field:'areaNum',hide:true,title:'库区序号',width:'1%'},
                          {field:'indexLeftTopX',title:'库区左上X坐标',width:'8%',edit: editable},
                          {field:'indexRightBottomX',title:'库区右下X坐标',width:'8%',edit: editable},
                          {field:'indexLeftTopY',title:'库区左上Y坐标',width:'8%',edit: editable},
                          {field:'indexRightBottomY',title:'库区右下Y坐标',width:'8%',edit: editable},
                          {field:'isEffective',title:'状态',width:'6%',templet:"#online-status"},
                          {title:'操作',width:'15%',toolbar: '#sys-area-tool'}
                      ]];
                  },
              };



      // table.render({
      //   elem:'#' + Page.tableId,
      //   url:Page.url,
      //   height:'600px',
      //   page:true,
      //   limits:[3,5,7,10,13,20,30],
      //   limit:13,
      //   autoSort:false,
      //   where: Page.where,
      //   cols:Page.initColumn()
      // });


      /**
       * 编辑
       */
      Page.openEdit = function (data) {
          layer.open({
              type : 2,
              title : '库区编辑',
              shadeClose : true,
              shade : 0.8,
              area: ['650px', '650px'],
              content : Page.queryUrl + "?id=" + data.idKey,
              btn : [ '确定', '取消' ],
              yes : function(index, layero) {
                   //点击确认触发 iframe 内容中的按钮提交
                  var submit = layero.find('iframe').contents().find("#form-btn-save");
                  submit.click();

                  //刷新表格
                  table.render();
              }
          });
      };


    $('#btnSearch').click(function (){
        Page.searchAction();
    });


    $('#btnReset').click(function (){
        Page.resetAction();
    });


    Page.resetAction = function (){
        $(".layui-input").val('');
        Page.searchAction();
    };

    function sleep (delay) {
        var start = (new Date()).getTime();

        while ((new Date()).getTime() - start < delay) {
            continue;
        }
    };

    /**
     * 渲染表格的方法
     */
    var generateTable = function(param) {
        /**
         * 表格渲染
         */
        treetable.render({
            elem: '#' + Page.tableId
            ,id:'areaTable'
            ,url: Page.url
            ,height: 'full-140'
            ,treeColIndex: 4   //树形图标显示在第几列
            ,treeSpid: -1     //最上级的父级id
            ,treeIdName: 'idKey'   //id字段的名称
            ,treePidName: 'parentId'  //父级节点字段
            ,treeDefaultClose: true   //是否默认折叠
            ,treeLinkage:false  //父级展开时是否自动展开所有子级
            ,page: false
            ,autoSort:false
            ,where:param
            ,toolbar: Page.toolbar
            ,defaultToolbar: []
            ,css: [
                // 对开启了编辑的单元格追加样式
                '.layui-table-view td[data-edit]{color: yellow;}'
            ].join('')
            ,cols: Page.initColumn()
            ,done: function(res, curr, count){
                // 获取当前行数据
                var options = this;
                table.getRowData = function(elem){
                    var index = $(elem).closest('tr').data('index');
                    console.log(index);
                    return table.cache['areaTable'][index] || {};
                };
                dropdown.render({
                    elem: '.materialNo-dropdpwn',
                    data: materialNoArray,
                    click: function(obj){
                        //物料编码更新
                        var data = table.getRowData( this.elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                        // 更新数据中对应的字段
                        data.materialNo = obj.title;
                        data.materialName = obj.id;
                        this.elem.find('span').text(obj.title);
                        this.elem.parents('td').next().find('span').text(obj.id);
                    }
                });

                dropdown.render({
                    elem: '.materialName-dropdpwn',
                    data: materialNameArray,
                    click: function(obj){
                        var data = table.getRowData(this.elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)

                        this.elem.find('span').html(obj.title);
                        // 更新数据中对应的字段
                        data.materialNo = obj.id;
                        data.materialName = obj.title;
                        this.elem.find('span').text(obj.title);
                        this.elem.parents('td').prev().find('span').text(obj.id);
                    }
                });


            }
        });
    }

    //渲染表格
    generateTable();


    Page.searchAction = function (){
        var spanNo= $("#spanName").val();
        var areaName= $("#areaName").val();
        var param = {spanNo:spanNo,areaName:areaName}

        generateTable(param);


        // table.render({
        //     elem:'#' + Page.tableId,
        //     url:Page.url,
        //     height:'600px',
        //     page:true,
        //     limits:[3,5,7,10,13,20,30],
        //     limit:13,
        //     autoSort:false,
        //     where: param,
        //     cols:Page.initColumn()
        // });
    };

    Page.openAdd = function (idKey){
        layer.open({
            type : 2,
            title : '库区新增',
            shadeClose : true,
            shade : 0.8,
            area: ['500px', '500px'],
            content : Page.addUrl + "?idKey="+idKey,
            btn : [ '确定', '取消' ],
            yes : function(index, layero) {
                //点击确认触发 iframe 内容中的按钮提交
                var submit = layero.find('iframe').contents().find("#form-btn-save");
                submit.click();
            },
            end:function (){
                generateTable();
            }

        });
    };



    /**
     * 表头工具栏
     */
    table.on('toolbar(' + Page.tableId + ')', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        var data = checkStatus.data;
        if(data == null || data.length == 0){
            CXL.warn("请选择一个库区进行新增操作");
            return;

        }

        switch(obj.event){
            case 'doAdd':
                var parentId = data[0].parentId;
                if(parentId != '-1'){
                    CXL.warn("所选库区不是一级库区,请选择一级库区进行新增操作");
                    return;
                }
                var idKey = data[0].idKey;  // 获取选中行数据
                Page.openAdd(idKey);
                break;
        };
    });


    /**
       * 表格工具栏
       */
      table.on('tool(' + Page.tableId + ')', function(obj){
         //获得当前行数据
        var data = obj.data;
         //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var layEvent = obj.event;


        //编辑操作
        if(layEvent === 'edit'){
          Page.openEdit(data);
        }

        if(layEvent === 'mod'){
            Page.mod(data);
        }

          if(layEvent === 'del'){
              Page.del(data.idKey);
          }

      });

    // 状态 - 开关操作
    form.on('switch(status-switch)', function(obj){
        //根据开关变更isEffective值状态
        var data = table.getRowData(obj.elem);
        if(obj.elem.checked){
            data.isEffective = 'Y';
        } else {
            data.isEffective = 'N';
        }


    });


    Page.mod = function (obj){


        //初始化操作
        $.ajax({
            type: "post",
            url: CXL.ctxPath + '/sys/area/saveChildArea',
            data:obj,
            success: function(res) {
                if(res.success) {
                    CXL.success(res.msg);
                } else {
                    CXL.warn(res.msg);
                }

            }
        });
    };



    Page.del = function (idKey){
        //初始化操作
        $.ajax({
            type: "post",
            url: CXL.ctxPath + '/sys/area/delChildArea',
            data:{idKey:idKey},
            success: function(res) {
                if(res.success) {
                    CXL.success(res.msg);
                    generateTable();
                } else {
                    CXL.warn(res.msg);
                }

            }
        });
    };





  })